package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.Strategy;
import cn.wolfcode.luowowo.domain.Travel;
import cn.wolfcode.luowowo.domain.UserInfo;
import cn.wolfcode.luowowo.query.TravelQuery;
import cn.wolfcode.luowowo.query.TypeMap;
import cn.wolfcode.luowowo.repository.TravelRepositoey;
import cn.wolfcode.luowowo.service.*;
import cn.wolfcode.luowowo.util.DBHelper;
import com.mongodb.DB;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.lang.reflect.Type;
import java.util.Date;
import java.util.List;

@Service
public class TravelServiceImpl implements ITravelService {

    @Autowired
    private TravelRepositoey travelRepositoey;
    @Autowired
    private IRegionService regionService;
    @Autowired
    private IDestinationService destinationService;
    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private MongoTemplate template;
    private Pageable pageable;

    @Override
    public List<Travel> list() {
        return travelRepositoey.findAll();
    }

    @Override
    public Travel selectOne(String id) {
        return travelRepositoey.findById(id).orElse(null);
    }

    @Override
    public Page<Travel> query(TravelQuery qo) {
        //创建查询对象
        Query query = new Query();
        //根据最热或者最新来查
        if (qo.getOrderType() == 1) {
            //最新
            query.with(Sort.by(Sort.Direction.DESC, "createTime"));
        } else {
            //最热
            query.with(Sort.by(Sort.Direction.DESC, "viewnum"));
        }
        //根据出行天数查询
        TypeMap per = qo.getPer();
        if (per != null) {
            query.addCriteria(Criteria.where("perExpend").gte(per.getMin()).lte(per.getMax()));
        }
        //根据旅游天数来查询
        TypeMap day = qo.getDay();
        if (day != null) {
            query.addCriteria(Criteria.where("day").gte(day.getMin()).lte(day.getMax()));
        }

        //根据目的地id查询
        if (StringUtils.hasLength(qo.getDestId())) {
            query.addCriteria(Criteria.where("destId").is(qo.getDestId()));
        }
        //页面显示集合
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        Page<Travel> query1 = DBHelper.query(template, Travel.class, query, pageable);
        for (Travel travel : query1) {
            //通过游记的用户id,查询所对应的用户设置进游记对象中
            UserInfo userInfo = userInfoService.selectById(travel.getUserId());
            travel.setAuthor(userInfo);
        }
        return query1;


    }
    public void save(Travel travel){
        //mongoDB中id是空字符串,添加的时候要先设置为null,不然不会自动将id封装到实体对象中
        travel.setId(null);
        travelRepositoey.save(travel);
    }

    @Override
    public void update(Travel travel) {
        if (StringUtils.hasLength(travel.getId())) {
            travelRepositoey.save(travel);
        }
    }

    @Override
    public void delete(String id) {
        travelRepositoey.deleteById(id);
    }


    @Override
    public List<Travel> queryViewnumTop3ByDestId(String destId) {
        //根据目的地id查询点击量前三的攻略,根据点击量倒序,跳过0个查三个
        Pageable pageable = PageRequest.of(0, 3, Sort.Direction.DESC, "viewnum");
        List<Travel> travels = travelRepositoey.findByDestId(destId, pageable);
        return travels;

    }

    /**
     * 通过游记id和传过来的状态来改变现有游记的状态
     *
     * @param id
     * @param state
     */
    @Override
    public void changeState(String id, int state) {
        Travel travel = this.selectOne(id);
        //判断游记是否存在
        if (travel != null) {
            //判断之前的状态是否是待审核状态或已发布状态
            if (travel.getState() == Travel.STATE_RELEASE || travel.getState() == Travel.STATE_WAITING) {
                //审核通过了的话要干什么?
                if (state == Travel.STATE_RELEASE) {
                    //审核通过时间的设置
                    travel.setReleaseTime(new Date());
                    //最后更新时间改动
                    travel.setLastUpdateTime(new Date());
                    //审核状态改成审核通过,已发布
                    travel.setState(state);
                } else if (state == Travel.STATE_REJECT) {
                    //审核拒绝的时候应该干嘛?
                    //最后更新时间的改动
                    travel.setLastUpdateTime(new Date());
                    //审核状态改成审核拒绝
                    travel.setState(state);
                    //审核通过时间设置为空
                    travel.setReleaseTime(null);
                }
                this.update(travel);
            }
        }

    }

    @Override
    public void saveOrUpdate(Travel travel) {
        /**
         * 游记的新增或者编辑
         */
        //判断游记是否存在
        if(travel != null){
            //需要额外添加的有
            //作者id,通过当前登录用户拿
            travel.setUserId(travel.getAuthor().getId());
            //目的地名字,通过目的地id拿
            travel.setDestName(destinationService.selectOne(travel.getDestId()).getName());
            //创建时间,当前时间
            travel.setCreateTime(new Date());
            //最后更新时间,当前时间
            travel.setLastUpdateTime(new Date());
        }
        //如果游记中带有id的话,那就是更新
        if(StringUtils.hasLength(travel.getId())){
            //需要额外更新的地方有:
            //title,coverUrl,traveTime,person,day,perExpend,destId,summary,content
            Query query = new Query();
            query.addCriteria(Criteria.where("_id").is(travel.getId()));
            DBHelper.update(template,query,travel,"title","coverUrl",
                    "traveTime","person","day","perExpend","destId",
                    "summary","content");
        }else{
            this.save(travel);
        }

    }

    @Override
    public Travel queryTrave(String id) {
        /**
         * 根据游记id查询对应游记中的用户id,再根据用户id查询对应用户设置进游记中
         * 根据游记id查询对应游记中的目的地,再根据目的地id查询对应目的地设置进游记中
         */
        if(StringUtils.hasLength(id)){
            Travel travel = this.selectOne(id);
            travel.setAuthor(userInfoService.selectById(travel.getUserId()));
            travel.setDest(destinationService.selectOne(travel.getDestId()));
            return travel;
        }
        return null;
    }

    @Override
    public Travel get(String id) {

        return this.selectOne(id);
    }

    @Override
    public List<Travel> findByDestName(String keyword) {
        List<Travel> list = travelRepositoey.findByDestName(keyword);
        for (Travel travel : list) {
            travel.setAuthor(userInfoService.selectById(travel.getUserId()));
        }
        return list;
    }


}

